import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:lottie/lottie.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class LottieRefreshHeader extends StatefulWidget {
  static double size = 120;

  @override
  State<LottieRefreshHeader> createState() => _LottieRefreshHeaderState();
}

class _LottieRefreshHeaderState extends State<LottieRefreshHeader>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  late AnimationController _repeatController;
  late Animation<double> _repeatAnimation;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      vsync: this,
      duration: Duration(
        milliseconds: 1000,
      ),
    );

    _animation = Tween<double>(
      begin: 0,
      end: 0.33,
    ).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Curves.linear,
      ),
    );

    _repeatController = AnimationController(
      vsync: this,
      duration: Duration(
        milliseconds: 3000,
      ),
    );

    _repeatAnimation = Tween<double>(
      begin: 0.33,
      end: 1,
    ).animate(
      CurvedAnimation(
        parent: _repeatController,
        curve: Curves.linear,
      ),
    );

    _repeatController.repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    _repeatController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CustomHeader(
      height: LottieRefreshHeader.size,
      builder: (BuildContext context, RefreshStatus? status) {
        return Container(
          height: LottieRefreshHeader.size,
          alignment: Alignment.topCenter,
          child: Lottie.asset(
            'assets/refresh.json',
            width: LottieRefreshHeader.size,
            height: LottieRefreshHeader.size,
            controller: status == RefreshStatus.refreshing ||
                    status == RefreshStatus.completed
                ? _repeatAnimation
                : _animation,
          ),
        );
      },
      onOffsetChange: (double offset) {
        _controller.animateTo(offset / LottieRefreshHeader.size,
            duration: Duration.zero);
      },
    );
  }
}
